package com.example.demo.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>Description: rocketmq消息组件</p>
 * <p>Date: 2020/7/9 14:09</p>
 *
 * @author Eric Lee
 * @version v1.0.0
 **/
@Configuration
@EnableConfigurationProperties({RocketMQProperties.class})
@ConditionalOnProperty(prefix = "rocketmq", name = "isEnable", havingValue = "true")
@Slf4j
public class RocketMQProducerConfig {

    @Autowired
    private RocketMQProperties rocketMQProperties;

    @Bean
    public DefaultMQProducer getRocketMQProducer() {

        String groupName = rocketMQProperties.getProducer().getGroupName();
        String nameserAddr = rocketMQProperties.getProducer().getNamesrvAddr();
        String instanceName = rocketMQProperties.getProducer().getInstanceName();

        DefaultMQProducer producer;
        producer = new DefaultMQProducer(groupName);
        producer.setNamesrvAddr(nameserAddr);
        producer.setInstanceName(instanceName);
        //如果需要同一个jvm中不同的producer往不同的mq集群发送消息，需要设置不同的instanceName
        producer.setMaxMessageSize(rocketMQProperties.getProducer().getMaxMessageSize());
        producer.setSendMsgTimeout(rocketMQProperties.getProducer().getSendMsgTimeout());
        //如果发送消息失败，设置重试次数，默认为2次
        Integer getRetryTimesWhenSendFailed = rocketMQProperties.getProducer().getRetryTimesWhenSendFailed();
        if (getRetryTimesWhenSendFailed != null) {
            producer.setRetryTimesWhenSendFailed(getRetryTimesWhenSendFailed);
        }
        try {
            producer.start();
        } catch (MQClientException e) {
            log.error("===生产者启动失败=== msg：" + e.getErrorMessage(), e);
        }
        return producer;
    }

}
